import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { DialogQueue } from '@/utils/dialogQueue'

export const useMultiSelectStore = defineStore('multiSelect', () => {
  // 状态
  const dialogQueue = new DialogQueue()
  const currentDialog = ref(null)
  const options = ref([])
  const selectedIndices = ref([])
  const defaultIndices = ref([])

  // 动作
  function show(titleText, optionsList, defaultSelectIndices = []) {
    return dialogQueue.show({
      onLoaded: () => {
        currentDialog.value = {
          title: titleText
        }
        options.value = optionsList
        selectedIndices.value = [...defaultSelectIndices].sort((a, b) => a - b)
        defaultIndices.value = [...defaultSelectIndices].sort((a, b) => a - b)
      }
    })
  }

  function toggleSelection(index) {
    const currentIndex = selectedIndices.value.indexOf(index)
    if (currentIndex === -1) {
      selectedIndices.value.push(index)
      selectedIndices.value.sort((a, b) => a - b)
    } else {
      selectedIndices.value.splice(currentIndex, 1)
    }
  }

  function confirm() {
    dialogQueue.hide(selectedIndices.value)
  }

  function cancel() {
    selectedIndices.value = [...defaultIndices.value]
    dialogQueue.hide(defaultIndices.value)
  }

  return {
    // 状态
    isVisible: dialogQueue.isVisible,
    title: computed(() => currentDialog.value?.title || ''),
    options,
    selectedIndices,
    // 动作
    show,
    toggleSelection,
    confirm,
    cancel,
    getQueueLength: dialogQueue.getQueueLength.bind(dialogQueue),
    clearQueue: dialogQueue.clearQueue.bind(dialogQueue)
  }
}) 